import axios from 'axios'
import config from './map.conf'
import Web from './map.web'
class Location_dd {
  getAddress(callback) {
    let corpCode = sessionStorage.getItem('dd_corp') || localStorage.getItem('dstore_corpId')
    if (!corpCode) {
      new Web().getAddress(callback)
      // callback({code: -1, msg: '钉钉编码'})
      return
    }
    axios.get('/auth/getAuthConfig.json', {
      params: {
        corp: corpCode,
        url: $tool.isIosOrAndroid() === 'android' ? window.initUrl : decodeURIComponent(location.href.split('#')[0]),
        client: 'ding'
      }
    }).then(res => {
      let rs = res.data
      let data = rs.data
      if (rs.code != '0' || !data || !data.signature) {
        callback({code: -1, msg: '无法获得鉴权信息'})
        return
      }
      window.dd.error(function (err) {
        console.error('dd error: ' + JSON.stringify(err))
        callback({code: -1, msg: '钉钉鉴权失败，无法获得当前位置信息'})
      })
      // 钉钉鉴权,获取钉钉配置信息
      window.dd.config({
        agentId: data.agentId,
        corpId: data.corpId,
        timeStamp: data.timeStamp,
        nonceStr: data.nonceStr,
        signature: data.signature,
        type: 0,
        jsApiList: [
          'device.geolocation.get'
        ]
      })
      dd.ready(function () {
        window.dd.device.geolocation.get({
          targetAccuracy: config.ACCURACY,
          coordinate: 1,
          withReGeocode: true,
          useCache: false, // 默认是true，如果需要频繁获取地理位置，请设置false
          onSuccess: function (ret) {
            callback({
              province: ret.province,
              city: ret.city,
              district: ret.district,
              address: ret.address,
              lon: ret.longitude,
              lat: ret.latitude
            })
            /* 高德坐标 result 结构
            {
                longitude : Number,
                latitude : Number,
                accuracy : Number,
                address : String,
                province : String,
                city : String,
                district : String,
                road : String,
                netType : String,
                operatorType : String,
                errorMessage : String,
                errorCode : Number,
                isWifiEnabled : Boolean,
                isGpsEnabled : Boolean,
                isFromMock : Boolean,
                provider : wifi|lbs|gps,
                accuracy : Number,
                isMobileEnabled : Boolean
            }
            */
          },
          onFail: function (err) {
            console.error(err)
            callback({code: -2, msg: '网络异常，无法获取当前位置'})
          }
        })
      })
    }).catch(err => {
      console.error(err)
      callback({code: -1, msg: '无法获得钉钉鉴权信息'})
    })
  }
}
export default Location_dd
